import { shuffle, cloneDeep, throttle, debounce } from 'lodash-es'
import { reactive, computed, onBeforeMount } from "vue"
import { isFunc, isStr, isObject, msg, eventCenter, log, setInitData, tableFormat } from '../utils'

export default (config: any, body: any) => {

    const state = reactive({
        tableData: [] as any[],
        dialog: {
            visible: false,
            config: {} as any,
            body: [] as any[],
        }
    })

    const defaultForm = computed(() => {
        return body.column
            ? body.column
                .filter((item: any) => !['button'].includes(item.ui) && item.form)
                .map((item: any) => {
                    return {
                        label: item.label,
                        key: item.key,
                        ...item.common ? item.common : {},
                        ...item.form ? item.form : {},
                    }
                })
            : []
    })

    const dialogFormClosed = () => state.dialog.visible = false

    // 获取表格数据
    const getTableData = async (_p = {}) => {
        const fetch = config.fetch
        if (!fetch) return log(`缺少 fetch 配置`, '', 'warn')
        if (!fetch.api) return log(`缺少 fetch.api 配置`, '', 'warn')
        if (fetch.validate && !fetch.validate({ msg })) return
        let p = {}
        if (fetch.before) p = fetch.before({})
        try {
            const { data } = await fetch.api({ ...p, ..._p})
            state.tableData = fetch.success && isFunc(fetch.success)
                ? fetch.success({ data, msg })
                : data
            // console.log('data', data, state.tableData);
            if (fetch.complete && isFunc(fetch.complete)) fetch.complete({ msg })
        } catch (error) {
            if (fetch.fail && isFunc(fetch.fail)) fetch.fail(error)
        }
    }

    // 创建弹窗
    const createDialog = ({params, isEmpty = false}: any) => {
        const { item, form } = params
        if (!item.options) return log(item.label, '缺少 options 配置', 'warn')
        state.dialog.config = item.options.config ? cloneDeep(item.options.config) : {}
        state.dialog.config.title = item.label
        state.dialog.config.parentData = cloneDeep({ ...form })
        state.dialog.config.parentInitData = cloneDeep({})
        state.dialog.body = cloneDeep([
            ...isEmpty ? [] : defaultForm.value,
            ...item.options.body || []
        ])
        state.dialog.visible = true
    }

    // 内置事件
    const action: any = {
        add: (params: any) => {
            state.tableData.unshift({
                id: `${new Date().getTime()}`,
            })
            config.edit && config.edit.update && config.edit.update({
                msg,
                data: state.tableData
            })
        },
        insert: ({ index, type }: any) =>{
            switch (type) {
                case 'addPrev':
                    state.tableData.splice(index, 0, { id: `${new Date().getTime()}` })
                    break
                case 'addNext':
                    state.tableData.splice(index + 1, 0, { id: `${new Date().getTime()}` })
                    break
                case 'remove':
                    state.tableData.splice(index, 1)
                    break
            }
            config.edit && config.edit.update && config.edit.update({
                msg,
                data: state.tableData
            })
        },
        batchDelete: (params: any) => {
            const { selection, item } = params
            if (!selection.length) return msg.warning('请选择要删除的数据')
            const ids = selection.map((_item: any) => _item[item.batchDeleteKey])
            state.tableData = state.tableData
                .filter((_item: any) => !ids.includes(_item[item.batchDeleteKey]))
            config.edit && config.edit.update && config.edit.update({
                action: { name: 'batchDelete', ids: ids },
                msg,
                data: state.tableData
            })
        },
        query: (params: any) => {
            getTableData({ queryData: params })
        },
        view: (params: any) => {
            const { item } = params
            state.dialog.visible = true
            state.dialog.config.title = item.label
            state.dialog.body = cloneDeep(defaultForm.value)
        },
        // 表单弹窗
        dialogForm: (params: any) => {
            createDialog({ params })
        },
        // 空白表单弹窗
        emptyDialogForm: (params: any) => {
            createDialog({ params, isEmpty: true })
        },
    }

    const init = () => {
        getTableData()
    }
    
    onBeforeMount(() => {
        init()
    })

    return {
        state,
        dialog: state.dialog,
        dialogFormClosed,
        action
    }
}